package is.web.htgen.table;

import java.util.Map;

/**
 *
 * @author aspr0
 */
public class Pager
{
    public static String generateHtml(int count, int cstart)
    {
        String html =
                "<div class=\"actionInput\">"
                + "<form method=\"post\">"
                + "Current page: %s. Go to page %s %s"
                + "</form>"
                + "</div>";
        String select = "<select name=\"start\" style=\"width:60px;\">%s</select>";
        String option = "<option value=\"%s\" %s>%s</option>";
        String submit = "<input type=\"submit\" value=\"go\" name=\"pager\">";

        String options = "";

        int perPage = 100;
        int pageNum = 0;
        int cpage = Math.round(cstart / perPage) + 1;

        do
        {
            pageNum++;
            int start = (pageNum - 1) * perPage + 1;
            String selected = (cpage + 1 == pageNum) ? "selected" : "";
            options += String.format(option, start, selected, pageNum);
        }
        while (count > pageNum * perPage);

        select = String.format(select, options);
        return String.format(html, cpage, select, submit);
    }

    /**
     * Replaces or adds 's' parameter.
     *
     * @param parameterMap
     * @return Location string scrolled to new page.
     */
    public static String generateQuery(Map<String, String[]> parameterMap, int start)
    {
        String query = "?";
        boolean startSet = false;

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet())
        {
            String name = entry.getKey();
            String value = entry.getValue()[0];

            if ("s".equals(name) || "pager".equals(name) || "start".equals(name))
            {
                /* Omitting pager, start and s params
                 * Start param goes to processing query before redirect
                 */
            }
            else
            {
                query += String.format("%s=%s&", name, value);
            }
        }

        query += String.format("s=%s&", start);

        return query;
    }
}
